<?php

namespace app\model;

use app\exception\PasswordErrorException;
use app\exception\TokenExpiredException;
use app\exception\UserNotFoundException;
use think\Model;

class User extends Model
{

    /**
     * 用户登录
     * @param $studentNumber string 学号
     * @param $password string 密码
     * @return array 用户信息
     */
    public static function login($studentNumber,$password)
    {
        // 用户查询
        $user = self::where("student_number",$studentNumber)->find();

        // 未查找到用户
        if (!$user) {
            throw new UserNotFoundException();
        }

        // 比较密码
        if (md5($password) != $user->password) {
            throw new PasswordErrorException();
        }

        // 生成token
        $salt = "linyongqi";
        $randomStr = uniqid(mt_rand(), true);
        $token =md5($randomStr . time() . $salt);


        // 更新token
        $user->save([
            'token' => $token
        ]);

        // 返回用户信息
        return [
            'token' => $token,
            'user' => $user->hidden(['password', 'token'])->toArray()
        ];

    }

    /**
     * 验证登录状态
     * @param $token
     * @return array
     * @throws UserNotFoundException
     * @throws TokenExpiredException
     */
    public static function isLogin($token)
    {
        // 用户查询
        $user = self::where("token",$token)->find();

        // 登录过期
        if (!$user) {
            throw new TokenExpiredException();
        }

        // 返回用户信息
        return [
            'user' => $user->hidden(['password', 'token'])->toArray()
        ];

    }
}